package com.junmeng.lib.ui.topview.core

import android.view.KeyEvent
import android.view.MotionEvent
import android.view.Window

/**
 * 拦截返回事件，提供监听器
 * @property originalCallback Callback
 */
class WindowBackPressedCallback(val originalCallback: Window.Callback) :
    Window.Callback by originalCallback {
    interface OnBackPressedListener {
        /**
         * 返回事件通知
         * @return Boolean 要表示消费此事件返回true,否则返回false
         */
        fun onBackPressed(): Boolean
    }

    private var mListenerList: MutableList<OnBackPressedListener> = mutableListOf()

    /**
     * 添加返回事件监听器
     * @param listener OnBackPressedListener
     */
    fun addOnBackPressedListener(listener: OnBackPressedListener) {
        mListenerList.add(listener)
    }

    /**
     * 移除返回事件监听器
     * @param listener OnBackPressedListener
     */
    fun removeOnBackPressedListener(listener: OnBackPressedListener) {
        mListenerList.remove(listener)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
            mListenerList.forEach {
                if (it.onBackPressed()) {
                    return true // 拦截返回事件
                }
            }
        }
        return originalCallback.dispatchKeyEvent(event)
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        return originalCallback.dispatchTouchEvent(event)
    }
}